
var Movie = require('../models/movie')
var _ = require('underscore')

// detail page
exports.detail = function(req, res){
	var id = req.params.id

	Movie.findById(id, function (err, movie) {
		if(err){
			console.log(err)
		}

		res.render('detail', { 
			title: 'imooc 详情页',
			movie: movie
		})
	})
}

// admin page
exports.add = function(req, res){
	res.render('admin', { 
		title: 'imooc 后台录入页',
		movie: {
			_id: '',
			doctor: '何塞·帕迪里亚',
			country: '美国',
			title: '机械战警',
			year: '2014',
			poster: 'http://r3.ykimg.com/05160000530EEB63675839160D0B79D5',
			language: '英语',
			flash: 'http://player.youku.com/player.php/sid/XNjA1Njc0NTUy/v.swf',
			summary: '影片的故事背景与原版基本相同，故事设定在2028年的底特律，男主角亚历克斯·墨菲是一名正直的警察，被坏人安装在车上的炸弹炸成重伤，为了救他，OmniCorp公司将他改造成了生化机器人“机器战警”，代表着美国司法的未来。'
		}
	})
}

// admin update movie
exports.update = function (req, res) {
	var id = req.params.id
	if(id){
		Movie.findById(id, function (err, movie) {
			if(err){
				console.log(err)
			}

			res.render('admin', { 
				title: 'imooc 后台编辑页',
				movie: movie
			})
		})

	}
}

// admin post movie
exports.save = function (req, res) {
	console.log(req.body.movie)
	var id = req.body.movie._id
	var movieObj = req.body.movie
	var _movie

	if (id != ''){
		Movie.findById(id, function (err, movie) {
			if(err){
				console.log(err)
			}

			_movie = _.extend(movie, movieObj)
			_movie.save(function (err, movie) {
				if(err){
					console.log(err)
				}

				res.redirect('/movie/' + movie._id)
			})
		})
	}
	else{
		_movie = new Movie({
			title: movieObj.title,
			doctor: movieObj.doctor,
			language: movieObj.language,
			year: movieObj.year,
			poster: movieObj.poster,
			summary: movieObj.summary,
			flash: movieObj.flash,
			country: movieObj.country
		})

		_movie.save(function (err, movie) {
			if(err){
				console.log(err)
			}

			res.redirect('/movie/' + movie._id)
		})
	}

}

// list page
exports.list = function(req, res){
	Movie.fetch(function (err, movies) {
		if(err){
			console.log(err)
		}

		res.render('list', { 
			title: 'imooc 列表页',
			movies: movies
		})

	})
	// res.render('list', { title: 'imooc 列表页',
	// 	movies: [{
	// 		title: '机械战警',
	// 		_id: 1,
	// 		doctor: '何塞·帕迪里亚',
	// 		country: '美国',
	// 		year: 2014,
	// 		language: '英语',
	// 		flash: 'http://player.youku.com/player.php/sid/XNjA1Njc0NTUy/v.swf'
	// 	}]
	// })
}


// list delete movie
exports.del = function (req, res) {
	var id = req.query.id;
	if (id){
		Movie.remove({_id: id}, function (err, movie) {
			if(err){
				console.log(err)
			}
			else {
				res.json({ 
					success: 1
				})
			}
		})
	}
}